import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Select,
  ConfigProvider,
  Table,
  Tag,
  Space,
  Popconfirm,
  message,
} from "antd";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import zhCN from "antd/locale/zh_CN";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import img404 from "@/assets/error.png";
import useChannels from "@/hooks/useChannels";
import { apiGetArticleList, apiDeleteArticleList } from "@/apis/article";
dayjs.locale("zh-cn");

const { Option } = Select;
const { RangePicker } = DatePicker;

const Article = () => {
  const [list, setList] = useState([]);
  const navigate = useNavigate();
  const [count, setCount] = useState(0);
  const [params, setParams] = useState({
    status: "",
    channel_id: "",
    begin_pubdate: "",
    end_pubdate: "",
    page: 1,
    per_page: 4,
  });
  const onSubmit = function (val) {
    setParams((pre) => {
      return {
        ...pre,
        status: val.status,
        channel_id: val.channel_id,
        begin_pubdate: val.date[0].format("YYYY-MM-DD"),
        end_pubdate: val.date[1].format("YYYY-MM-DD"),
      };
    });
  };
  //   获取文章列表
  useEffect(() => {
    const getList = async function () {
      const res = await apiGetArticleList(params);
      setCount(res.data.total_count);
      setList(res.data.results);
    };
    getList();
  }, [params]);
  const channels = useChannels();
  const pageChange = function (pagination, filters, sorter) {
    setParams((pre) => {
      return {
        ...pre,
        page: pagination.current,
      };
    });
  };
  const onConfirm = async function (data) {
    await apiDeleteArticleList(data.id);
    message.success("删除成功");
    setParams({
      ...params,
    });
  };
  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      width: 120,
      render: (cover) => {
        return (
          <img src={cover.images[0] || img404} width={80} height={60} alt="" />
        );
      },
    },
    {
      title: "标题",
      dataIndex: "title",
      width: 220,
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (data) => {
        if (data === 2) {
          return <Tag color="green">审核通过</Tag>;
        } else {
          return <Tag color="magenta">审核不通过</Tag>;
        }
      },
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
    },
    {
      title: "操作",
      render: (data) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => navigate(`/publish?id=${data.id}`)}
            />
            <Popconfirm
              title="确定删除该条文章吗"
              onConfirm={() => onConfirm(data)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <ConfigProvider locale={zhCN}>
      <div>
        <Card
          title={
            <Breadcrumb
              items={[
                {
                  title: <Link to="/">首页</Link>,
                },
                {
                  title: "文章管理",
                },
              ]}
            />
          }
          style={{ marginBottom: 20 }}
        >
          <Form
            initialValues={{ status: undefined, channel_id: 1 }}
            onFinish={onSubmit}
          >
            <Form.Item label="状态" name="status">
              <Radio.Group>
                <Radio value={undefined}>全部</Radio>
                <Radio value={0}>草稿</Radio>
                <Radio value={1}>待审核</Radio>
                <Radio value={2}>审核通过</Radio>
                <Radio value={3}>审核失败</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item label="频道" name="channel_id">
              <Select placeholder="请选择文章频道" style={{ width: 120 }}>
                {channels.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="日期" name="date">
              <RangePicker />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ marginLeft: 80 }}
              >
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
          <Table
            rowKey="id"
            columns={columns}
            dataSource={list}
            pagination={{
              defaultCurrent: 1,
              total: count,
              pageSize: params.per_page,
              position: ["bottomCenter"],
            }}
            onChange={pageChange}
          />
        </Card>
      </div>
    </ConfigProvider>
  );
};

export default Article;
